var myAds = {
    layoutUrl:"",
    ajaxParam:'', 
    loadAction: function(url, data_post, container, message, block, callbackFunction, isChildDiv, stripScript, isPretty) {
        var post_data = '';    
        if(data_post != '' || data_post != null){
            for( var key in data_post){
                post_data +="&"+key+"="+data_post[key];
            }
        }
        myAds.ajaxParam = jQuery.ajax({
            type: "POST",
            url: url,
            data: post_data,
            cache: false,
            beforeSend: function(){
                
                if( block){
                    if(jQuery("#loading").css('display') == 'none'){
                        
                        if(isPretty){                            
                            jQuery.blockUI({
                                message: jQuery('#loading'),
                                css: {
                                    border: 'none',
                                    padding: '15px',
                                    backgroundColor: '#000',
                                    '-webkit-border-radius': '10px',
                                    '-moz-border-radius': '10px',
                                    'border-radius': '10px',
                                    opacity: .5,
                                    color: '#fff',
                                    'z-index': 10000
                                },
                                overlayCSS: {
                                    backgroundColor: 'transparent'
                                }

                            });                             
                        }else{
                            jQuery.blockUI({
                                message: jQuery('#loading'),
                                css: {
                                    border: 'none',
                                    padding: '15px',
                                    backgroundColor: '#000',
                                    '-webkit-border-radius': '10px',
                                    '-moz-border-radius': '10px',
                                    'border-radius': '10px',
                                    opacity: .5,
                                    color: '#fff',
                                    'z-index': 10000
                                },
                                overlayCSS: {
                                    backgroundColor: 'transparent'
                                }
                            
                            });
                        }
                    }
                    jQuery("#loading").fadeIn("fast");
                }else{
                    myAds.showLoadingIcon(container);
                }
            }, //show loading just when link is clicked
            complete: function(){
                if( block){
                    jQuery("#loading").fadeOut("fast");
                    jQuery.unblockUI();
                }else{
                    myAds.hideLoadingIcon();
                }
            }, //stop showing loading when the process is complete
            success: function(data){
                
                if(stripScript){
                    data = myAds.stripScript(data);
                }
                if(!isChildDiv){
                    data = data.replace(/<script type="text\/javascript" src="/g, '<script type="text\/javascript" src1="');
                    jQuery(container).html(data);
                    data = data.replace(/id="/g, 'id1="');
                    jQuery('#stExtra').html(data);
                }else{
                    data = data.replace(/<script type="text\/javascript" src="/g, '<script type="text\/javascript" src1="');
                    jQuery('#stExtra').html(data);
                    var html = jQuery('#stExtra ' + container).html();
                    jQuery('#stExtra div#main').remove();
                    jQuery(container).html(html);
                    jQuery('.stcontainer #stExtra').html(''); //remove loading id
                }
                jQuery(container).css('display', 'block');
                if(message){
                    myAds.sendMessage(message);
                }
                if(callbackFunction){
                    callbackFunction.call(this, data);
                }
            }
        });
    },
    loadUploadButton: function(thumbnail_width, url, callBackfunction, pathFolder, mainForm){
        
        if(!pathFolder)
            pathFolder = '';        
        if(!thumbnail_width){
            thumbnail_width = '';
        }
        jQuery(document).ready(function(){
            jQuery('.image_upload_button').each(function(){
                var clickedObject = jQuery(this);
                var clickedID = jQuery(this).attr('id');
                new AjaxUpload(clickedID, {
                    action: url,
                    name: clickedID, // File upload name
                    data: { // Additional data to send
                        //                        action: action,
                        ajax: 1,
                        type: 'upload',
                        data: clickedID,
                        pathFolder: pathFolder,
                        thumbnail_width: thumbnail_width
                    },
                    autoSubmit: true, // Submit file after selection
                    responseType: false,
                    onChange: function(file, extension){},
                    onSubmit: function(file, extension){
                        clickedObject.text('Uploading'); // change button text, when user selects file
                        this.disable(); // If you want to allow uploading only 1 file at time, you can disable upload button
                        interval = window.setInterval(function(){
                            var text = clickedObject.text();
                            if (text.length < 13){
                                clickedObject.text(text + '.');
                            }
                            else {
                                clickedObject.text('Uploading');
                            }
                        }, 200);
                    },
                    onComplete: function(file, response) {
                        window.clearInterval(interval);
                        clickedObject.text('Choose image');
                        this.enable(); // enable upload button
                        if(response == '|*|'){
                            alert('Your upload file is incorrect');
                            return false
                        }
                        //                        alert(response);
                        var response1 = response.split('|*|');
                        var file1 = response1[0];
                        var file2 = response1[1];
                        var buildReturn = '';
                        

                        // If there was an error
                        if(file1.search('Upload Error') > -1){
                            buildReturn = '<span class="upload-error">' + file1 + '</span>';
                            jQuery(".upload-error").remove();
                            jQuery('#img_preview_holder').html(buildReturn);
                        }
                        else{      
                            var html = jQuery('#image_'+clickedID).html();
                            html = html.replace('<br clear="all">', '');                            
                            buildReturn = '<div class="img_preview_holder">';
                            buildReturn += '<img alt="" src="'+file2+'" class="preview">';
                            buildReturn += '<a class="image_reset_button" src="'+file1+'" href="javascript:" title="Remove">';
                            buildReturn += '<img src="/lgdmember/admin/../application/admin/externals/images/icon_delete.png" class="icon_delete">';
                            buildReturn += '</a>';
                            buildReturn += '</div>'; 
                            html += buildReturn+'<br clear="all">';
                            jQuery(".upload-error").remove();
                            jQuery('#image_'+clickedID).html(html);
                            jQuery('#image_'+clickedID).fadeIn();
                            
                            html = '<input name="image[]" value="'+file1+'" type="hidden" class="img_input" />';
                            jQuery(mainForm).append(html);
                            if(jQuery('h3 .tip').css('display') == 'none')
                                jQuery('h3 .tip').fadeIn();
                        }
                        if(callBackfunction){
                            callBackfunction.call(this, response);
                        }
                    }
                });

            });
        });
    },
    loadRemoveButton: function(url, callBackfunction, pathFolder){
        if(!pathFolder)
            pathFolder = '';
        jQuery(document).ready(function(){
            jQuery('.image_reset_button').click(function(){
                clickedObject = jQuery(this);
                var src = clickedObject.attr('src');
            
                var ajax_url = url;
                
                var data = {
                    ajax: 1,
                    file: src,
                    pathFolder: pathFolder
                };
                //            alert(src);
                jQuery( "#dialog-confirm" ).dialog({
                    modal: true,
                    buttons: {
                        "Confirm deletion": function() {
                            jQuery( this ).dialog( "close" );
                            jQuery.blockUI({
                                message: jQuery('#loading'),
                                css: {
                                    border: 'none',
                                    padding: '15px',
                                    backgroundColor: '#000',
                                    '-webkit-border-radius': '10px',
                                    '-moz-border-radius': '10px',
                                    'border-radius': '10px',
                                    opacity: .5,
                                    color: '#fff',
                                    'z-index': 10000
                                },
                                overlayCSS: {
                                    backgroundColor: 'transparent'
                                }

                            });  
                            jQuery("#loading").fadeIn("fast");
                            jQuery.post(ajax_url, data, function(response) {
                                if(callBackfunction){
                                    callBackfunction.call(this, clickedObject);
                                }
                                clickedObject.parent().remove();
                                jQuery('.img_input').each(function(){
                                    if(jQuery(this).val() == src){
                                        jQuery(this).remove();
                                        
                                    }
                                });
                                jQuery("#loading").fadeOut("fast");
                                jQuery.unblockUI();
                                
                            });
                        },
                        Cancel: function() {
                            jQuery( this ).dialog( "close" );
                        }
                    }
                });
                jQuery("#dialog-confirm").dialog("open");

                return false;
                
            });
        });
    },
    showLoadingIcon: function(container){  
        jQuery('.loadingIcon').remove();   
        jQuery(container).after("<div class='loadingIcon'></div>");
        jQuery('.loadingIcon').fadeIn(); 
    },
    hideLoadingIcon: function(){
        jQuery('.loadingIcon').remove();        
    },    
    sendMessage: function(data){
        jQuery(document).ready(function(){
            try{
                data = eval('('+data+')');
            }catch (e){}

            if(typeof(data)=='string'){
                var message = data;
                var status = 'message';
            }else{
                message = data['message'];
                status = data['status'];
            }
            if(status == 'success'){
                jQuery('.notification' ).removeClass('notification_error');
                jQuery('.notification' ).removeClass('notification_message');
                jQuery('.notification' ).addClass('notification_success');
                jQuery('.notification .text strong').html('Success!');
            }else if(status == 'message'){
                jQuery('.notification' ).removeClass('notification_error');
                jQuery('.notification' ).removeClass('notification_success');
                jQuery('.notification' ).addClass('notification_message');
                jQuery('.notification .text strong').html('Message!');
            }else{
                jQuery('.notification' ).removeClass('notification_message');
                jQuery('.notification' ).removeClass('notification_success');
                jQuery('.notification' ).addClass('notification_error');
                jQuery('.notification .text strong').html('Error!');
            }
            jQuery('.notification .text span').html(message);
            jQuery('.notification').fadeIn('slow');

            jQuery('.notification').click(function() {
                jQuery(this).fadeOut(800);
            });
            window.setTimeout(function(){
                jQuery('.notification').fadeOut();
            }, 2500);
        });
 
    },
    sortingInit: function(url, currentSort, container){
        jQuery(document).ready(function(){
            jQuery( container + ' th a').each(function(){
                var href = jQuery(this).attr('href');
                href = href.split('sorting/');
                url = href[0];
                href = href[1];
                var params = href.split('/');
                if(params[0] == currentSort && currentSort != ''){
                    var currentType = jQuery.trim(params[2]).toUpperCase().replace('%20', '');
                    href = url+ 'sorting/'+params[0]+'/type/'+currentType;
                    jQuery(this).attr('id', jQuery.trim(params[0]));
                    jQuery(this).attr('sort_type', currentType);
                    //                    jQuery(this).attr('sort_url', url.trim());
                    //                    jQuery(this).attr('class', 'cur');
                    jQuery(this).attr('href', href); 
                    if(currentType.toUpperCase() == 'DESC')
                        jQuery(this).append('<span class="icon_desc"></span>');
                    else
                        jQuery(this).append('<span class="icon_asc"></span>');
                }else{
                    href = url+ 'sorting/'+params[0]+'/type/ASC';
                    jQuery(this).attr('id', jQuery.trim(params[0]));
                    jQuery(this).attr('sort_type', 'ASC');
                    //                    jQuery(this).attr('sort_url', url.trim());
                    jQuery(this).attr('href', href); 
                    jQuery(this).children('span').remove();
                }
            });
        });
 
    },
    shortAction: function(containerID, url){
        jQuery(document).ready(function(){
            jQuery(containerID+" tr").click(function () {
                url = url.split('/uid/');
                url = url[0];
                var id;
                id = jQuery(this).attr("alt");
                if(id > 0){
                    location.href = url+'/uid/'+id;
                }

            });
        });
    
    },
    ajaxSearchInit: function(container, url, keyName, extraCondition) {
        jQuery(document).ready(function(){
            jQuery(container).append('<ul id="ajaxSuggest" class="ajaxSuggest"></ul>');     
            jQuery(container+ ' input').keyup(function(){
                myAds.ajaxSearch(container, url, keyName, extraCondition)
            });            
            
            jQuery(container+ ' input').focus(function(){
                jQuery(container + ' #ajaxSuggest').css('display', 'block');
            });
            
        });
    },
    ajaxSearch: function(container, url, keyName, extraCondition) {
        if(myAds.ajaxParam != ''){
            myAds.ajaxParam.abort();
        }
        var data_post = new Array();
        data_post['keyWord'] = jQuery(container + ' input').val();
        data_post['tableName'] = jQuery(container + ' input').attr('tableName');
        data_post['extraCondition'] = extraCondition;
        if(keyName.constructor == Array){
            data_post['keyName'] = '';
            for(var i=0 in keyName){
                if(keyName[i])
                    data_post['keyName'] += keyName[i]+',';
            }
        }else{
            data_post['keyName'] = keyName;
        }
        myAds.loadAction(url, data_post, container + ' #ajaxSuggest', null, false, function(){
            jQuery(container+' #ajaxSuggest').fadeIn();
            jQuery(container+' ul#ajaxSuggest li').click(function(){
                var html  = jQuery(this).html();
                html = html.replace(/<.*?>/g, '');
                html = html.replace(/&nbsp;/g, ' ');
                jQuery(container + ' input').val(html);
                jQuery(container+' #ajaxSuggest').fadeOut();
                jQuery(container+' input').focus(); 
                jQuery(container+' form').submit();
            });
            myAds.ajaxSortCallBack = function(data_post){
                data_post['keyWord'] = jQuery(container + ' form input').val();
            }
            myAds.pagingCallback = function(data_post){
                data_post['keyWord'] = jQuery(container + ' form input').val();
            }
        });
                
    },
    paging: function(page_num, key_page, url, container, isChildDiv, isPretty){
        var data_post = new Array();
        data_post[key_page] = page_num;

        jQuery(container+' th a').each(function(){
            if(jQuery(this).attr('class') == 'cur'){
                data_post[container+'_sorting'] = jQuery(this).attr('id');
                var type = jQuery(this).attr('sort_type');
                if(type.toUpperCase() == 'DESC')
                    data_post[container+'_type'] = 'ASC';
                else
                    data_post[container+'_type'] = 'DESC';
            }
        }); 
        myAds.pagingCallback(data_post);
        myAds.loadAction(url, data_post, container, null, true, function(){
            myAds.sortAjaxInit(url, data_post[container+'_sorting'], container);
            jQuery('.ajaxSuggest').fadeOut();
            myAds.pagingCallbackFunction(data_post);
        }, isChildDiv, true, isPretty);
    },
    onSubmitForm: function(form, container, block, isChildDiv, isStripScript, callback_function){
        if(myAds.ajaxParam != ''){
            myAds.ajaxParam.abort();
        }
        jQuery(document).ready(function(){ 
            jQuery(form).validate({
                errorPlacement: function(error, element) {
                    //error.appendTo( element.parent());
                    element.parent().addClass('error');
                    myAds.hideLoadingIcon();
                },
                submitHandler: function() {                    
                    if(!myAds.extraValidateForm()){
                        return;                    
                    }
                    if(block){
                        if(jQuery("#loading").css('display') == 'none'){
                            jQuery.blockUI({
                                message: jQuery('#loading'),
                                css: {
                                    border: 'none',
                                    padding: '15px',
                                    backgroundColor: 'transparent',
                                    '-webkit-border-radius': '10px',
                                    '-moz-border-radius': '10px',
                                    'border-radius': '10px',
                                    opacity: 1,
                                    color: '#fff',
                                    'z-index': 10000
                                },
                                overlayCSS: {
                                    backgroundColor: '#fff'
                                }

                            }); 
                        }
                        jQuery("#loading").fadeIn("fast");
                    }else{
//                        myAds.showLoadingIcon('.showIconLoad');
                    }
                    jQuery('#stExtra').html('');
                    
                    jQuery.post(jQuery(form).attr('action'), jQuery(form).serialize(),function(data, textStatus){
                        myAds.hideLoadingIcon();
                        if(isStripScript){
                            data = myAds.stripScript(data);
                        }else{
                            data = data.replace(/<script type="text\/javascript" src="/g, '<script type="text\/javascript" src1="');
                        }
                        if(!isChildDiv){
                            
                            jQuery(container).html(data);
                            if(!container){
                                data = data.replace(/id="/g, 'id1="');
                                jQuery('#stExtra').html(data);
                            }
                        }else{
//                            data = data.replace(/id="/g, 'id1="');
                            jQuery('#stExtra').html(data);
                            var html = jQuery('#stExtra ' + container).html();
                            jQuery('#stExtra').html('');
                            jQuery(container).html(html);
                            
                        }
                        if(jQuery.isFunction(callback_function)){
                            callback_function.call(this, data);
                        }
                        //if(jQuery("#loading").css('display') != 'none'){
                        jQuery.unblockUI();
                        jQuery("#loading").fadeOut('normal');
                        jQuery('.ajaxSuggest').fadeOut();
                        myAds.extraValidateForm = function(){
                            return true;
                        };
                    //                        }
                    });
                }

            });
        });
    },
    stripScript: function(s) {
        var div = document.createElement('div');
        div.innerHTML = s;
        var scripts = div.getElementsByTagName('script');
        var i = scripts.length;
        while (i--) {
            scripts[i].parentNode.removeChild(scripts[i]);
        }
        return div.innerHTML;
    },
    sortAjaxInit: function(url, currentSort, container){
        jQuery(document).ready(function(){
            jQuery( container + ' th a').each(function(){
                var href = jQuery(this).attr('href');
                href = href.split('sorting/');
                url = href[0];
                href = href[1];
                var params = href.split('/');
                if(params[0] == currentSort && currentSort != ''){
                    var currentType = jQuery.trim(params[2]).toUpperCase().replace('%20', '');
                    href = url+ 'sorting/'+params[0]+'/type/'+currentType;
                    jQuery(this).attr('id', jQuery.trim(params[0]));
                    jQuery(this).attr('sort_type', currentType);
                    jQuery(this).attr('sort_url', jQuery.trim(url));
                    jQuery(this).attr('class', 'cur');
                    jQuery(this).attr('href', 'javascript:void(0)'); 
                    if(currentType.toUpperCase() == 'DESC')
                        jQuery(this).append('<span class="icon_desc"></span>');
                    else
                        jQuery(this).append('<span class="icon_asc"></span>');
                }else{
                    var sorting = params[0];
                    href = url+ 'sorting/'+sorting+'/type/ASC';
                    jQuery(this).attr('id', jQuery.trim(sorting));
                    jQuery(this).attr('sort_type', 'ASC');
                    jQuery(this).attr('sort_url', jQuery.trim(url));
                    jQuery(this).attr('href', 'javascript:void(0)'); 
                    jQuery(this).children('span').remove();
                }
            });
            jQuery(container + ' th a').click(function(){
                var data_post = new Array();
                data_post[container+'_sorting'] = jQuery(this).attr('id');
                url = jQuery(this).attr('sort_url');
                data_post[container+'_type'] = jQuery(this).attr('sort_type');
                myAds.ajaxSortCallBack(data_post);
                myAds.loadAction(url, data_post, container, null, true, function(){
                    myAds.sortAjaxInit(url, data_post[container+'_sorting'], container);
                }, true, true);
            });
        });
    },
    ajaxSortCallBack: function(){},
    pagingCallback: function(){},
    pagingCallbackFunction: function(){},
    switchButtonInitialize: function(name){
        jQuery(document).ready( function(){
            jQuery('.cb-enable').each(function(){
                var key = jQuery(this).attr('key');
                var checkboxValue = jQuery(this).attr('id_value');
                var value = jQuery(this).attr('value');
                if(checkboxValue)
                    jQuery(this).html('<input value_default ="'+value+'" type="hidden" name="data['+name+']'+checkboxValue+'" value="'+value+'" />');
                if(jQuery.cookie(key) == 'disable' && key != 'undefined' && key){
                    //                    alert(jQuery.cookie(key));
                    myAds.switchButton(this);
                }
            });
            jQuery('.cb-disable').each(function(){
                var checkboxValue = jQuery(this).attr('id_value');
                var value = jQuery(this).attr('value');
                if(checkboxValue){
                    jQuery(this).html('<input value_default ="'+value+'" type="hidden" name="data['+name+']'+checkboxValue+'" value="0" />');
                }
                var key = jQuery(this).attr('key');
                if(jQuery.cookie(key) == 'enable' && key != 'undefined' && key){
                    //                    alert(jQuery.cookie(key)+'+'+key);
                    myAds.switchButton(this);
                }
            });
        });
    },
    switchButton: function(_this, isCookie, callbackFunction){
        if(isCookie == 'undefined'){
            isCookie = true;
        }
        var key = jQuery(_this).attr('key');
        if(jQuery(_this).hasClass('cb-disable')){
            jQuery(_this).addClass('cb-enable');
            jQuery(_this).removeClass('cb-disable');
            var checkboxValue = jQuery(_this).children("input").attr('value_default');
            jQuery(_this).children("input").val(checkboxValue);
            if(key != 'undefined' && key && isCookie)
                jQuery.cookie(key, 'enable' );
        }else{
            jQuery(_this).addClass('cb-disable');
            jQuery(_this).removeClass('cb-enable');
            jQuery(_this).children("input").val(0);
            //            jQuery(_this).children("input").attr('checked', false);
            if(key != 'undefined' && key && isCookie)
                jQuery.cookie(key, 'disable');
        }
        if(jQuery.isFunction(callbackFunction)){
            callbackFunction.call();
        }
        
    },
    switchAllButton: function(_this, container){        
        if(jQuery(_this).hasClass('cb-disable')){
            jQuery(container+' .cb-disable').each(function(){
                var id = jQuery(this).attr('id');
                if(id != 'all'){
                    myAds.switchButton(this);
                }                
            });            
        }else{
            jQuery(container+' .cb-enable').each(function(){
                var id = jQuery(this).attr('id');
                if(id != 'all'){
                    myAds.switchButton(this);
                }  
            });
        }
        myAds.switchButton(_this, false);
    },
    extraValidateForm: function(){
        return true;
    },  
    dialogConfirm: function(title, message, btnLabel, submiFunction){
        jQuery( "#dialog-confirm" ).html("<p>"+message+"</p>");
        jQuery( "#dialog-confirm" ).attr('title', title);
        jQuery( "#dialog-confirm" ).dialog({
            resizable: false,
            modal: true,
            buttons: {
                Yes: 
                function() {
                    jQuery( this ).dialog( "close" );
                    if(jQuery.isFunction(submiFunction)){
                        submiFunction.call();
                    }
                },
                No: function() {
                    jQuery( this ).dialog( "close" );
                }
            }
        });
        jQuery("#dialog-confirm").dialog("open");
        return false;
    }
    
};

